<script setup lang="tsx">
import {computed, reactive, ref, watch} from 'vue';
import {useFormRules, useNaiveForm} from '@/hooks/common/form';
import {$t} from '@/locales';
import {SelectOption} from "naive-ui";
import {fetchGetAllRoles} from "@/service/api/roles";

import {fetchAddUser} from "@/service/api/users";

defineOptions({
  name: 'UserOperateDrawer'
});


interface Props {
  operateType: Api.Common.OperateType;
  rowData?: Api.Entity.User | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const {formRef, validate, restoreValidation} = useNaiveForm();
const {defaultRequiredRule, patternRules} = useFormRules();
const roleId = ref();
const title = computed(() => {
  const titles: Record<Api.Common.OperateType, string> = {
    add: $t('page.manage.user.addUser'),
    edit: $t('page.manage.user.editUser')
  };
  return titles[props.operateType];
});

type Model = Pick<
  Api.Entity.User,
  'nickName' | 'phoneNumber' | 'email' | 'role'
>;

const model: Api.Entity.User = reactive(createDefaultModel());

function createDefaultModel(): Api.Entity.User {
  return {
    enabled: true,
    nickName: '',
    phoneNumber: '',
    email: '',
    role: null
  };
}

type RuleKey = Extract<keyof Model, 'nickName' | 'phoneNumber' | 'email'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  nickName: defaultRequiredRule,
  phoneNumber: defaultRequiredRule,
  email: {
    ...defaultRequiredRule,
    ...patternRules.email
  }

};

const roleOptions = ref<SelectOption[]>([]);

async function getRoleOptions() {
  const {error, data} = await fetchGetAllRoles();
  if (!error && data) {
    for (let i = 0; i < data.length; i++) {
      let item = data[i];
      roleOptions.value.push({
        label: item.name,
        value: Number(item.id)
      })
    }
  }
}

function handleUpdateModelWhenEdit() {
  if (props.operateType === 'add') {
    Object.assign(model, createDefaultModel());
    return;
  }

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
    roleId.value = props.rowData.role?.id
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  if (props.operateType === 'add') {
    model.params = {
      roleId: roleId.value
    }
    const {error} = await fetchAddUser(model);
    if (!error) {
      window.$message?.success('添加成功');
      closeDrawer();
      emit('submitted');
    }
  } else if (props.operateType === 'edit') {
    window.$message?.success($t('common.updateSuccess'));
  }


}

watch(visible, () => {
  if (visible.value) {
    handleUpdateModelWhenEdit();
    restoreValidation();
    getRoleOptions();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" :title="title" display-directive="show" :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem label="邮箱地址" path="email">
          <NInput v-model:value="model.email"/>
        </NFormItem>

        <NFormItem label="手机号码" path="phoneNumber">
          <NInput v-model:value="model.phoneNumber"/>
        </NFormItem>
        <NFormItem label="密码" path="password">
          <NInput v-model:value="model.password"/>
        </NFormItem>
        <NFormItem label="姓名" path="nickName">
          <NInput v-model:value="model.nickName"/>
        </NFormItem>
        <NFormItem label="角色" path="roles">
          <n-select v-model:value="roleId" :options="roleOptions" :placeholder="$t('page.manage.user.form.userRole')"/>
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
